// pages/antiforget/antiforget.js
//获取应用实例
const app = getApp()
let tool = require('../../utils/tool.js');
const httpUtils = require('../../utils/httpUtils.js');
const utils = require('../../utils/util.js');
const versionutil = require('../../utils/versionutil.js');

//antiforgetList中 sort  21格序号；status 0 未复习 1 已复习 2 无学习任务或者未到复习时间 3 缺卡

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    isVip: false, //vip为	0 游客 1 VIP
    showVipModal: false,
    flag: true, //开通会员提示弹窗的标志
    completflag: true, //已完成复习状态下提示弹窗的标志
    vipNums: 0,
    oLater: false,
    reviewWordNums: 0, //今日需复习的单词数
    add_time: '', //学习时间
    type: 1, //1 不能右划 2 不能左划 3 可以左右划 4 默认（仅用于错误返回）
    antiforgetList: [], // 21天抗遗忘数据列表
    antiArrayNum: [], //有多少个21数组的数据；[1,2 ...] 
    // cur: 0, //改变swiper的当前索引
    // curindex: 0, //当前的索引,
    myDate: '', //当前的时间戳
    animstate: 'paused',
    review_status: 2, //复习状态 0 复习完成可查看错词；1有复习单词；2 今日无复习任务；3未到复习时间
    push_time: '19:00', //推送时间
    is_write:0, //该学生是否写作课 0为默认没有，1为有写作
    is_has_homework:0, //是否有未完成的作文作业：0否，1是
    // animList:[],
    // animation:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
  
  },

  /**
   * 当swiper左右滑动切换改变时
   */
  swiperChange: function(e) {
    var that = this;
    //滑动改变后当前的页下标current
    let current = e.detail.current;
    //当前所在页的日期的时间戳（类似于日历的月份）
    let curTimestamp = that.data.myDate;

    if (current < that.data.curindex) {
      //右滑 ----日期减20天
      curTimestamp = curTimestamp - 1000 * 60 * 60 * 24 * 20;
    } else if (current > that.data.curindex) {
      //左滑-----日期加20天
      curTimestamp = curTimestamp + 1000 * 60 * 60 * 24 * 20;
    }
    let startTime = utils.formatDate(new Date(curTimestamp));
    console.log("startTime="+startTime);
    that.setData({
      add_time: startTime,
      curindex: current,
      myDate: curTimestamp,
    })
    //请求数据详情
    console.log("swiperChange()获取21方格数据")
    that.getAntiForgetData();
  },

  /**
   * 回到今天
   */
  toToday: function() {
    var that = this;
    //获取当前日期
    let nowDate = utils.formatDate(new Date());
    that.setData({
      add_time: nowDate,
      myDate: new Date().getTime(),
      cur: that.data.antiArrayNum.length == 0 ? 0 : that.data.antiArrayNum.length - 1,
      curindex: that.data.antiArrayNum.length == 0 ? 0 : that.data.antiArrayNum.length - 1,
    })

    //请求数据详情
    that.getAntiForgetData();
  },

  /**
   *  获取21天复习日历数据
   */
  getAntiForgetData: function() {
    var that = this;
    that.setData({
      antiforgetList: []
    })
    httpUtils.getAntiForgetData({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      add_time: that.data.add_time,
    }).then((res) => {
      let list = res.data.list;
      let datestr = res.data.date.replace(/-/g, "/");
      console.log("datestr:", datestr);
      // //给数组list新添加两个left,top属性 
      // for (let i = 0; i < list.length; i++) {
      //   list[i]['left'] = leftList[i];
      //   list[i]['top'] = topList[i];
      // }
      //设置值
      that.setData({
        antiforgetList: list,
        reviewWordNums: res.data.num,
        antiArrayNum: res.data.arr_num,
        isVip: res.data.vip == 1 ? true : false,
        vipNums: res.data.vip_num,
        review_status: res.data.review_status,
        push_time: res.data.push_time,
        myDate: new Date(datestr).getTime(),
        is_write:res.data.essayNum, 
        is_has_homework:res.data.has_one,
      });
      //获取当前日期
      let nowDate = utils.formatDate(new Date());
      if (that.data.add_time == nowDate) {
        that.setData({
          cur: that.data.antiArrayNum.length == 0 ? 0 : that.data.antiArrayNum.length - 1,
          curindex: that.data.antiArrayNum.length == 0 ? 0 : that.data.antiArrayNum.length - 1,
        })
      }
      //执行一次动画
      // that.beginAnimation();  
      that.setData({
        animstate: 'running'
      })
      console.log(that.data.animstate)
    });
  },



  /**
   * 上下平移动画
   */
  beginAnimation: function() {
    let that = this;
    let animList = that.data.animList;
    let animation = that.data.animation;
    for (let i = 0; i < that.data.antiforgetList.length; i++) {
      animation = wx.createAnimation({
        duration: 300,
        timingFunction: "linear",
        delay: 300 * (i + 2),
      });
      animation.translate(0, -20).step().translate(0, 0).step()
      animList[i] = animation;
    }
    for (let i = 0; i < that.data.antiforgetList.length; i++) {
      that.data.antiforgetList[i]['moves'] = animList[i].export()
    }
    that.setData({
      antiforgetList: that.data.antiforgetList,
    });
  },


  //跳转今日复习界面
  // toTodayReview: function() {
  toTodayReview:utils.throttle(function(e) {
    //没开通会员的点击复习按钮弹窗提示； 开通的跳转今日复习（学后检测）界面
    let that = this;
    console.log("点击今日复习按钮，vipnums="+that.data.vipNums)
    if (that.data.isVip === false) {
      this.setData({
        flag: false, //弹出试用框
        vipNums: that.data.vipNums,
        oLater: that.data.vipNums > 0 ? false : true
      })
      return false;
    } else {
      console.log("that.data.review_status:", that.data.review_status)
      // 0 复习完成可查看错词；1有复习单词；2 今日无复习任务；3未到复习时间
      let reviewStatus = that.data.review_status;
      // if (reviewStatus === 0) {
      //   //  0 复习完成  可跳转查看错词界面进行查看；
      //   this.setData({
      //     completflag: false, //弹出已复习完的提示框，并可点击查看错词
      //   })
      // } else {
      //   wx.navigateTo({
      //     url: '/pages/testReport/testReport?reviewNum=' + this.data.reviewWordNums + '&reviewStatus=' + reviewStatus + '&push_time=' + that.data.push_time,
      //   })
      // }
      let nowDate = utils.formatDate(new Date());
      wx.navigateTo({
        url: '/pages/reviewRecord/todayreview/todayreview?date='+nowDate+'&reviewStatus=' + reviewStatus + '&push_time=' + that.data.push_time+'&source=0',
      })
    }
  },1000),

  // 跳转到四种玩法界面
  goGames: function(e) {
    app.globalData.studyDate ="";
    wx.navigateTo({
      url: '/pages/review/review?from_channel=0',
    })
  },

  
  //跳转到学习记录界面
  gotorecord:function(){
    wx.navigateTo({
      url: '/pages/studyRecord/studyRecordList/studyRecordList',
    })
  },

  //查看作文作业
  gotohomework:function(){
    let that = this;
    if (that.data.isVip === false) {
      that.setData({
        showVipModal: true,
      })
      return false;
    }else{
      wx.navigateTo({
        url: '/pages/studyRecord/essaywork/essaywork',
      })
    }
 
  },
   /**点击组件弹窗中的开通vip按钮 */
  goOpen:function(){
    wx.navigateTo({
      url: "/pages/vip/vipBuy",
    });
    this.setData({
      showVipModal: false,
    })
  },

  /**点击弹窗的开通vip按钮 */
  govip: function(e) {
    wx.navigateTo({
      url: e.currentTarget.dataset.urldata,
    });
  },

  //暂缓开通
  openlater: function() {
    let that=this;
    this.setData({
      flag: true
    })
    let reviewStatus = this.data.review_status;
    // if (reviewStatus === 0) {
    //   //  0 复习完成  可跳转查看错词界面进行查看；
    //   this.setData({
    //     completflag: false, //弹出已复习完的提示框，并可点击查看错词
    //   })
    // } else {
    //   // wx.navigateTo({
    //   //   url: '/pages/testReport/testReport?reviewNum=' + this.data.reviewWordNums + '&reviewStatus=' + this.data.review_status + '&push_time=' + this.data.push_time,
    //   // })
    // }
    let nowDate = utils.formatDate(new Date());
    wx.navigateTo({
      url: '/pages/reviewRecord/todayreview/todayreview?date='+nowDate+'&reviewStatus=' + reviewStatus + '&push_time=' + that.data.push_time+'&source=0',
    })
  },

  /**关闭modal弹窗 */
  closeMask: function() {
    this.setData({
      flag: true
    })
    wx.showTabBar()
  },

  /**已完成今日复习，点击跳转查看错词界面 */
  lookWrongWords: function() {
    this.setData({
      completflag:true
    })
    wx.navigateTo({
      url: '/pages/antiforget/wrongWords/wrongWords',
    })
  },

  /**关闭完成modal弹窗 */
  closeCompletMask: function() {
    this.setData({
      completflag: true
    })
    wx.showTabBar()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //获取当前日期
    let nowDate = utils.formatDate(new Date());
    console.log("onshow()方法中，nowdate=", nowDate+",获取21方格数据")
    that.setData({
      add_time: nowDate,
      myDate: new Date().getTime(),
      cur: that.data.antiArrayNum.length == 0 ? 0 : that.data.antiArrayNum.length - 1,
      curindex: that.data.antiArrayNum.length == 0 ? 0 : that.data.antiArrayNum.length - 1,
    })
    //请求数据详情
    console.log("onshow--请求数据")
    that.getAntiForgetData();
  
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    let that = this;
    that.setData({
      animstate: 'paused'
    })
    console.log("onHide:", that.data.animstate)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },


    //点击请求订阅消息
    subscribeMessage(){
      let that =this;
      let tempId=['Bul3Aare2qoGLj0WhNr9ih-Y6aPKQToh5jXrmZ02XHU']; //需要订阅的消息模板的id的集合,一条或多条
  
      wx.requestSubscribeMessage({
        tmplIds: tempId,
        success (res) {
          if (res[tempId] === 'accept') {
            console.log('用户同意了')  
           //请求后端接口
          //  that.cloudSendMsg();
  
          }else if(res[tempId] == 'reject') { // 用户拒绝授权
            wx.showModal({
              title: '温馨提示',
              content: "您已关闭消息推送，如需要消息推送服务，请点击确定跳转设置页面打开授权后再次尝试。",
              success: function(modal) {
                  if (modal.confirm) { // 点击确定
                      wx.openSetting({ withSubscriptions: true })
                  }
              }
          })
          }
         },
         fail(err) { 
           console.log(err)
           if (err.errCode == '20004') {
            wx.showModal({
                title: '温馨提示',
                content: "您的消息订阅主已关闭，如需复习提醒服务，请点击确定跳转设置页面打开授权后再次尝试。",
                success: function(modal) {
                    if (modal.confirm) { // 点击确定
                        wx.openSetting({ withSubscriptions: true })
                    }
                }
            })
        }
          },
          complete(res) {
            console.log('complete  调用完成')
            // 无论取消还是接收都会执行:比如 下单(无论订阅号是取消还是接收都执行)
            that.toTodayReview();
          }
      })
    }


})